package com.xuelang.pipeline.infrastructure.pipeline.repository;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuelang.hiforce.base.tracing.TracingUtils;
import com.xuelang.pipeline.client.common.result.PageRecord;
import com.xuelang.pipeline.client.pipeline.dto.PipelineInstanceQuery;
import com.xuelang.pipeline.domain.pipeline.PipelineInstance;
import com.xuelang.pipeline.domain.pipeline.repository.PipelineInstanceRepository;
import com.xuelang.pipeline.infrastructure.pipeline.converter.PipelineInstanceToDOConverter;
import com.xuelang.pipeline.infrastructure.pipeline.dataobject.PipelineInstanceDO;
import com.xuelang.pipeline.infrastructure.pipeline.mapper.PipelineInstanceMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>流水线实例仓库接口实现类</p>
 *
 * @author : yixin.lys
 * @date : 2024-06-19 09:54
 **/
@Repository
public class PipelineInstanceRepositoryImpl implements PipelineInstanceRepository {

    @Autowired
    private PipelineInstanceMapper mapper;

    @Override
    public PageRecord<PipelineInstance> pageByPipelineCode(long currentPage, long pageSize, PipelineInstanceQuery pipelineInstanceQuery) {
        currentPage = currentPage < 1 ? 1 : currentPage;
        pageSize = pageSize < 1 ? 10 : pageSize;
        Page<PipelineInstanceDO> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<PipelineInstanceDO> wrapper = Wrappers.lambdaQuery(PipelineInstanceDO.class);
        wrapper.eq(StringUtils.isNotBlank(pipelineInstanceQuery.getPipelineCode()), PipelineInstanceDO::getPipelineCode, pipelineInstanceQuery.getPipelineCode());
        wrapper.eq(StringUtils.isNotBlank(pipelineInstanceQuery.getInstanceCode()), PipelineInstanceDO::getInstanceCode, pipelineInstanceQuery.getInstanceCode());
        wrapper.eq(pipelineInstanceQuery.getPipelineStatus() != null, PipelineInstanceDO::getPipelineStatus, pipelineInstanceQuery.getPipelineStatus());
        wrapper.apply(pipelineInstanceQuery.getStartTime() != null, "START_TIME >= {0}", pipelineInstanceQuery.getStartTime());
        wrapper.apply(pipelineInstanceQuery.getEndTime() != null, "START_TIME <= {0}", pipelineInstanceQuery.getEndTime());

        wrapper.orderByDesc(PipelineInstanceDO::getStartTime);
        Page<PipelineInstanceDO> pageResult = mapper.selectPage(page, wrapper);
        if (Objects.nonNull(pageResult)) {
            return new PageRecord<>(
                    page.getCurrent(),
                    page.getSize(),
                    page.getTotal(),
                    page.getPages(),
                    page.getRecords().stream().map(PipelineInstanceToDOConverter.INSTANCE::fromDO).collect(Collectors.toList())
            );
        }
        return null;
    }

    @Override
    public List<PipelineInstance> listByQuery(PipelineInstanceQuery pipelineInstanceQuery) {
        LambdaQueryWrapper<PipelineInstanceDO> wrapper = Wrappers.lambdaQuery(PipelineInstanceDO.class);
        if(Objects.nonNull(pipelineInstanceQuery)) {
            wrapper.eq(StringUtils.isNotBlank(pipelineInstanceQuery.getPipelineCode()),
                    PipelineInstanceDO::getPipelineCode, pipelineInstanceQuery.getPipelineCode());
            wrapper.eq(StringUtils.isNotBlank(pipelineInstanceQuery.getInstanceCode()),
                    PipelineInstanceDO::getInstanceCode, pipelineInstanceQuery.getInstanceCode());
            wrapper.eq(StringUtils.isNotBlank(pipelineInstanceQuery.getApplicationCode()),
                    PipelineInstanceDO::getApplicationCode, pipelineInstanceQuery.getApplicationCode());
            wrapper.eq(StringUtils.isNotBlank(pipelineInstanceQuery.getComponentLabel()),
                    PipelineInstanceDO::getComponentLabel, pipelineInstanceQuery.getComponentLabel());
        }
        wrapper.orderByDesc(PipelineInstanceDO::getStartTime);
        List<PipelineInstanceDO> found = mapper.selectList(wrapper);
        if (CollectionUtil.isNotEmpty(found)) {
            return found.stream().map(PipelineInstanceToDOConverter.INSTANCE::fromDO).collect(Collectors.toList());
        }
        return null;
    }

    private String getUserId(String userId) {
        String getUserId = TracingUtils.getUserId();
        return StrUtil.isBlank(getUserId) ? "-1" : getUserId;
    }

    @Override
    public void add(PipelineInstance pipelineInstance) {
        mapper.insert(PipelineInstanceToDOConverter.INSTANCE.toDO(pipelineInstance));
    }

    @Override
    public void update(PipelineInstance pipelineInstance) {
        mapper.updateById(PipelineInstanceToDOConverter.INSTANCE.toDO(pipelineInstance));
    }

    @Override
    public void removeByIds(List<String> idList) {
        mapper.deleteBatchIds(idList);
    }

    @Override
    public void removeByCodes(List<String> codeList) {
        LambdaQueryWrapper<PipelineInstanceDO> wrapper = Wrappers.lambdaQuery(PipelineInstanceDO.class);
        wrapper.in(PipelineInstanceDO::getPipelineCode, codeList);
        mapper.delete(wrapper);
    }

    @Override
    public PipelineInstance queryByCode(String pipelineInstanceCode) {
        PipelineInstanceDO pipelineInstanceDO = mapper.selectOne(Wrappers.lambdaQuery(PipelineInstanceDO.class).eq(PipelineInstanceDO::getInstanceCode, pipelineInstanceCode));
        return PipelineInstanceToDOConverter.INSTANCE.fromDO(pipelineInstanceDO);

    }
}
